<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/2/12
 * Time: 15:56
 */

namespace Kordar\Tree;

class ParentFinder
{
    private $parent = [];

    public function __construct($tree, $field, $value, $self = false)
    {
        $this->preSearchParent($tree, $field, $value, $self);
    }

    private function preSearchParent($tree, $field, $value, $self)
    {
        if ($tree === null) {
            return false;
        }

        if ($tree->data[$field] == $value) {
            if ($self) {
                $this->parent[] = $tree->data;
            }
            return true;
        }

        if ($this->preSearchParent($tree->left, $field, $value, $self)) {
            $this->parent[] = $tree->data;
            return true;
        }

        return $this->preSearchParent($tree->right, $field, $value, $self);
    }

    public function getParent($col = null)
    {
        return $col !== null ?
            array_column($this->parent, $col) :
            $this->parent;
    }

}